let express = require('express');
let crypto = require('crypto');
let router = express.Router();
let filter = require('../../components/filter');

/**
 * 查询用户数据 by p 2018-06-11
 *
 * 按条件查询用户数据
 *
 */
router.get('/', filter.authorize, function (req, res, next) {
    let params = req.query;

    var limits = "";
    var sql = "";
    var datas = [];

    req.app.db.query("select count(1) as totalCount from user " + sql, datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results[0].totalCount === 0) {
            res.json({"success": true, "data": {}, "totalCount": 0});
            return;
        }

        let totalCount = results[0].totalCount;

        if (params.pageNo > 0 && params.pageSize > 0) {
            limits = " limit ?, ?";
            datas.push((params.pageNo - 1) * params.pageSize);
            datas.push(params.pageSize * 1);
        }

        req.app.db.query("select * from user " + limits, datas, function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "data": results, "totalCount": totalCount, "message": ""});
        });
    });
});

/**
 * 查看用户数据 by p 2018-06-11
 *
 * 按id查看指定的用户信息
 */
router.get('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query("select * from user where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
});

/**
 * 修改用户数据 by p 2018-06-11
 *
 * 用户登录名、用户密码、是否登录过不允许修改
 */
router.put('/:id', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;

    if (params.id === undefined || params.id === '' || params.id <= 0) {
        res.json({"success": false, "message": "用户编码错误！"});
        return;
    }

    if (params.trueName === undefined || params.trueName === "") {
        res.json({"success": false, "message": "真实姓名不能为空！"});
        return;
    }

    if (params.roleId === undefined || params.roleId === "" || params.roleId === 0) {
        res.json({"success": false, "message": "必须指定用户角色！"});
    }

    if (params.departmentId === undefined || params.departmentId === "") {
        res.json({"success": false, "message": "必须指定用户所属部门！"});
        return;
    }

    req.app.db.query("select * from role where id = ?", [params.roleId], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "角色信息错误！"});
            return;
        }

        let role = results[0];

        req.app.db.query("select * from department where id = ?", [params.departmentId], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            if (results.length === 0) {
                res.json({"success": false, "message": "部门信息错误！"});
                return;
            }

            let department = results[0];
            let now = new Date();

            req.app.db.query("update user set trueName = ?, roleId = ?, roleName = ?, departmentId = ?, departmentName = ?, addr = ?, tel = ?, email = ?, userId = ?, userName = ?, updateDate = ? where id = ?", [params.trueName, role.id, role.name, department.id, department.name, params.addr, params.tel, params.email, user.id, user.trueName, now, params.id], function (err, results) {
                if (err) {
                    res.json({"success": false, "message": global.databaseErr, "detail": err});
                    return;
                }

                res.json({"success": true, "message": global.putMsg});
            });
        });
    });
});

/**
 * 新增用户数据 by p 2018-06-11
 *
 * 用户密码默认为  123456
 */
router.post('/', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;

    if (params.name === undefined || params.name === "") {
        res.json({"success": false, "message": "用户名不能为空！"});
        return;
    }

    if (params.trueName === undefined || params.trueName === "") {
        res.json({"success": false, "message": "真实姓名不能为空！"});
        return;
    }

    if (params.roleId === undefined || params.roleId === "" || params.roleId === 0) {
        res.json({"success": false, "message": "必须指定用户角色！"});
        return;
    }

    if (params.departmentId === undefined || params.departmentId === "") {
        res.json({"success": false, "message": "必须指定用户所属部门！"});
        return;
    }

    // 校验是否有重复用户名
    req.app.db.query("select * from user where name = ?", [params.name], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length > 0) {
            res.json({"success": false, "message": "用户名重复！"});
            return;
        }

        req.app.db.query("select * from role where id = ?", [params.roleId], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            if (results.length === 0) {
                res.json({"success": false, "message": "角色信息错误！"});
                return;
            }

            let role = results[0];

            req.app.db.query("select * from department where id = ?", [params.departmentId], function (err, results) {
                if (err) {
                    res.json({"success": false, "message": global.databaseErr, "detail": err});
                    return;
                }

                if (results.length === 0) {
                    res.json({"success": false, "message": "部门信息错误！"});
                    return;
                }

                let department = results[0];
                let md5 = crypto.createHash("md5");
                let password = md5.update("123456").digest('hex');
                let now = new Date();

                req.app.db.query("insert into user(name, trueName, password, roleId, roleName, departmentId, departmentName, addr, tel, email, loginTimes, userId, userName, createDate, updateDate, logged) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [params.name, params.trueName, password, role.id, role.name, department.id, department.name, params.addr, params.tel, params.email, 0, user.id, user.trueName, now, now, 0], function (err, results) {
                    if (err) {
                        res.json({"success": false, "message": global.databaseErr, "detail": err});
                        return;
                    }

                    res.json({"success": true, "message": global.postMsg});
                });
            });
        });

    });
});

/**
 * 修改用户密码 by v 2018-06-29
 *
 *
 */
router.post('/:id/changePassword', filter.authorize, function (req, res, next) {
    let params = req.body;
    let id = req.session.user.id;

    if (params.oldPassword === undefined || params.oldPassword === "") {
        res.json({"success": false, "message": "用户原密码不能为空！"});
        return;
    }

    if (params.newPassword === undefined || params.newPassword === "") {
        res.json({"success": false, "message": "用户新密码不能为空！"});
        return;
    }

    let oldMd5 = crypto.createHash("md5");
    let oldPassword = oldMd5.update(params.oldPassword).digest('hex');

    // 校验用户原密码是否正确
    req.app.db.query("select * from user where id = ? and password = ?", [id, oldPassword], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "用户原密码错误！"});
            return;
        }

        let newMd5 = crypto.createHash("md5");
        let newPassword = newMd5.update(params.newPassword).digest('hex');
        req.app.db.query("update user set password = ?, logged = 1 where id = ?", [newPassword, id], function (err, results) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "message": "密码修改成功！"});
        });
    });
});

/**
 * 初始化用户密码 by v 2018-06-29
 *
 *
 */
router.post('/:id/initPassword', filter.authorize, function (req, res, next) {
    let id = req.params.id;
    let md5 = crypto.createHash("md5");
    let password = md5.update("123456").digest('hex');

    req.app.db.query("update user set password = ?, logged = 0 where id = ?", [password, id], function (err, results) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": "密码初始化成功, 当前密码为 123456"});
    });
});

/**
 * 删除用户信息 by v 2018-06-11
 *
 * 按id删除指定的用户信息
 */
router.delete('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query('delete from user where id = ?', [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "message": global.deleteMsg});
    });
});

module.exports = router;